//
//  HRSoundCoverViewController.m
//  Hear
//
//  Created by mac on 2017/6/6.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRSoundCoverViewController.h"
#import "NSMutableAttributedString+GDAttString.h"
#import "OSSImageUploader.h"
#import "HRDynamicModel.h"
#import "HRPostDynamicViewModel.h"
#import "HRUpdataUserInfoModel.h"

#import "HRPostSoundViewModel.h"
#import "HRPostSoundModel.h"

#import "UzysImagePickerController.h"
#import "VPImageCropperViewController.h"
#import "UIImage+BlurEffects.h"

#import "HRShowPowerControlView.h"
#import "HRContactsManager.h"
#import "HRLocationViewModel.h"
#import "YContactObject.h"
#import "HRPhoneLoginViewController.h"
#import "HearNavigationController.h"
@interface HRSoundCoverViewController ()<UzysImagePickerControllerDelegate,VPImageCropperDelegate>
@property (nonatomic, strong)UIImage *selectImage;
@property (nonatomic, strong)HRPostSoundViewModel *saveSoundModel;
@property (nonatomic, strong)NSArray *descArray;
@property (nonatomic, assign)NSInteger tempIndex;
@property (nonatomic, strong)UIButton *enterButton;
@property(nonatomic, strong)UIImageView *coverImageView;
@property (nonatomic, strong)HRLocationViewModel *locationViewModel;

@end

@implementation HRSoundCoverViewController
#pragma mark - Get and Set
- (HRLocationViewModel *)locationViewModel{
    if (_locationViewModel == nil) {
        _locationViewModel = [[HRLocationViewModel alloc] init];
    }
    return _locationViewModel;
}


-(HRPostSoundViewModel *)saveSoundModel{
    if (_saveSoundModel == nil){
        _saveSoundModel = [HRPostSoundViewModel new];
    }
    return _saveSoundModel;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"声音名片封面";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupView];
    
    
    
    WeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![[HRContactsManager shareInstance]hasOpenContactsPower]){
            if (ISOPENTADDRESSBOOK)return;
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShowRemendOpenAddressBook"];
            
            NSMutableArray *mobileNumArr = [NSMutableArray array];
            [[HRContactsManager shareInstance] requestContactsComplete:^(NSArray<YContactObject *> * _Nonnull contacts) {
                
                //开始赋值
                for (YContactObject *object in contacts) {
                    YContactPhoneObject *phontObject = [object.phoneObject firstObject];
                    NSString *mobileNumStr = [phontObject.phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    if ([mobileNumStr isMobileNumber]){
                        DDLog(@"phoneNumber========================%@",mobileNumStr);
                        [mobileNumArr addObject:mobileNumStr];
                    }
                    
                }
                [weakSelf postSaveUserContacts:[mobileNumArr jsonStringEncoded]];
            }];
        }
    });
//    self.imageArray = @[@"soundcover1",@"soundcover2",@"soundcover3",@"soundcover4",@"soundcover5",@"soundcover6",@"soundcover7",@"soundcover8",@"soundcover9"];
//    
//    self.descArray = @[@"复古",@"黑白",@"简约",@"魅惑",@"怦然心动",@"洒脱",@"田园",@"甜美",@"月光"];

}

- (void)postSaveUserContacts:(NSString *)MobileList{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"MobileList"] = MobileList;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    [self.locationViewModel postSaveUserContacts:paramDict isSeccess:^(BOOL isSeccess) {
        [MBProgressHUD hideHUDForView:WINDOW animated:YES];
    }];
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)setupView{
    
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIButton *enterButton = [UIButton buttonWithType:0];
    enterButton.size = CGSizeMake(40, 20);
    enterButton.titleLabel.font = CustomUIFont(13);
    [enterButton setTitle:@"确定" forState:0];
    [enterButton addTarget:self action:@selector(enterButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:enterButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.enterButton = enterButton;
    
    
    CGFloat leftPading = 10;
    
    

    
//    CGFloat layWidth = (kFullWidth-3*leftPading)/2;
    
    
    UIImageView *cirleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"圆"]];
    cirleImageView.userInteractionEnabled = YES;
    [self.view addSubview:cirleImageView];
    cirleImageView.frame = CGRectMake((kFullWidth-240)/2, 120, 240, 240);
    
    WeakSelf
    self.coverImageView = [UIImageView new];
    self.coverImageView.userInteractionEnabled = YES;
    [cirleImageView addSubview:self.coverImageView];
    self.coverImageView.layer.cornerRadius = 220/2;
    self.coverImageView.clipsToBounds = YES;
    self.coverImageView.userInteractionEnabled = YES;
    self.coverImageView.frame = CGRectMake(10, 10, cirleImageView.width-20, cirleImageView.width-20);
    self.coverImageView.image = [UIImage imageNamed:@"Hear_record_相册@2x(1)"];
    UITapGestureRecognizer *coverTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf openPhotoClick];
    }];
    [self.coverImageView addGestureRecognizer:coverTap];
    

    
    UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftPading, cirleImageView.bottom+50, kFullWidth-leftPading*2, 80)];
    descLabel.numberOfLines = 0;
    descLabel.attributedText = [NSMutableAttributedString attStringFromTextForChatting:@"Hearer是以音会友的地方\r\n请点击上方选择一张展现你自己的照片作为封面" textFont:CustomUIFont(14)];
    descLabel.textAlignment = 1;
    descLabel.textColor = FirstTextColor;
    [self.view addSubview:descLabel];
}


- (void)openPhotoClick{
    UzysImagePickerController * UzysImageP = [[UzysImagePickerController alloc] init];
    [UzysImageP showInViewContrller:self maxCount:1 delegate:self];
    
}

- (void)UzysImagePickerDidFinishWithImages:(NSArray *)imageArray{
    dispatch_async(dispatch_get_main_queue(), ^{
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:[imageArray firstObject] cropFrame:CGRectMake(0, 100, kFullWidth, adjuctFloat(280)) limitScaleRatio:3.0];
        imgCropperVC.delegate = self;
        [self presentViewController:imgCropperVC animated:YES completion:nil];
    });
}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage{
     dispatch_async(dispatch_get_main_queue(), ^{
         [cropperViewController dismissViewControllerAnimated:YES completion:nil];
//         if (![self faceDetectWithImage:editedImage]){
//             [MBProgressHUD showMessage:@"请上传正脸照片" finishBlock:nil];
//             return;
//         }
         
         self.coverImageView.image = editedImage;
         
         self.selectImage = editedImage;
     });
}


- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController{
    dispatch_async(dispatch_get_main_queue(), ^{
        [cropperViewController dismissViewControllerAnimated:YES completion:nil];
    });
}



#pragma mark - 识别人脸
- (BOOL)faceDetectWithImage:(UIImage *)image {
    // 图像识别能力：可以在CIDetectorAccuracyHigh(较强的处理能力)与CIDetectorAccuracyLow(较弱的处理能力)中选择
    NSDictionary *opts = [NSDictionary dictionaryWithObject:
                          CIDetectorAccuracyLow forKey:CIDetectorAccuracy];
    // 将图像转换为CIImage
    CIImage *faceImage = [CIImage imageWithCGImage:image.CGImage];
    CIDetector *faceDetector=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:opts];
    // 识别出人脸数组
    NSArray *features = [faceDetector featuresInImage:faceImage];
    // 得到图片的尺寸
    CGSize inputImageSize = [faceImage extent].size;
    //将image沿y轴对称
    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, -1);
    //将图片上移
    transform = CGAffineTransformTranslate(transform, 0, -inputImageSize.height);
    
    // 取出所有人脸
    for (CIFaceFeature *faceFeature in features){
        // 判断是否有左眼位置
        if(faceFeature.hasLeftEyePosition){
            DDLog(@"======================有左眼");
            
        }
        // 判断是否有右眼位置
        if(faceFeature.hasRightEyePosition){
            DDLog(@"======================有右眼");
        }
        // 判断是否有嘴位置
        if(faceFeature.hasMouthPosition){
            DDLog(@"======================有嘴");
        }
        
        return YES;
        
    }
    return NO;
}



- (void)enterButtonClick{
    if (!self.selectImage){
        [MBProgressHUD showMessage:@"请上传一个封面" finishBlock:nil];
        return;
    }
    [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];

    self.enterButton.enabled = NO;
    [OSSImageUploader asyncUploadSound:@[self.outPutFilePath] complete:^(NSArray<NSString *> *names, UploadImageState state) {
        if (state == UploadImageFailed){
            self.enterButton.enabled = YES;
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            return;
        }
        NSString *soundUrl = [NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]];
        
        [OSSImageUploader asyncUploadImage:[self getBigIamgeWithALAsset:self.selectImage] complete:^(NSArray<NSString *> *names, UploadImageState state) {
            if (state == UploadImageFailed){
                self.enterButton.enabled = YES;
                [MBProgressHUD hideHUDForView:WINDOW animated:YES];
                return;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enterButton.enabled = YES;
                if (self.isFromGuide){
                    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:soundUrl] forKey:@"fromGuideSoundUrl"];
                    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]]] forKey:@"fromGuideImageUrl"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.timeStr forKey:@"fromGuideSoundLentgh"];

                    
                    [self.navigationController removeFromParentViewController];
                    UIWindow *window = [UIApplication sharedApplication].keyWindow;
                    [window removeAllSubviews];
                    window = nil;
                    HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRPhoneLoginViewController new]];
                    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                }else{
                    [self postSound:soundUrl andImageUrl:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]]];
                }
            });
            
        }];
        
        
    }];
    
    
    
    
}


- (UIImage*)getBigIamgeWithALAsset:(UIImage *)set{
    //压缩
    // 需传入方向和缩放比例，否则方向和尺寸都不对
    NSData *imageData = [self getBigIamgeDataWithALAsset:set];
    
    
    return [UIImage imageWithData:imageData];
}

- (NSData*)getBigIamgeDataWithALAsset:(UIImage *)set{
    ;
    
    return UIImageJPEGRepresentation(set, 0.5);
}

- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

- (void)postSound:(NSString *)soundUrl andImageUrl:(NSString *)imageUrl{
    
    [MBProgressHUD hideHUDForView:WINDOW animated:YES];

    
    HRPostSoundRequestModel *requstModel = [HRPostSoundRequestModel new];
    requstModel.LocalId = USERID;
    requstModel.UserLocalId = USERID;
    requstModel.SoundUrl = soundUrl;
    requstModel.SoundLength = self.timeStr;
    requstModel.CreateTime = [self getCurrentTime];
    requstModel.BackGround = @"soundcover2";
    requstModel.SoundTag = @"3";
    requstModel.BackGroundPhoto = imageUrl;
    
    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:soundUrl] forKey:@"SoundUrl"];

    WeakSelf
    [self.saveSoundModel postSoundParam:requstModel isSeccess:^(BOOL isSeccess) {
        self.enterButton.enabled = YES;

        if (isSeccess){
            [[NSUserDefaults standardUserDefaults] setObject:imageUrl forKey:@"BackGroundPhoto"];

            [weakSelf postDynamic:soundUrl];
            if (weakSelf.isFromLogin){
                [MBProgressHUD showMessage:@"生成成功" finishBlock:nil];
                [weakSelf.navigationController removeFromParentViewController];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                [window removeAllSubviews];
                window = nil;
                [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];

                
            }else{
                [MBProgressHUD showMessage:@"更改成功" finishBlock:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadHearView" object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }else{
            [MBProgressHUD showMessage:@"发送失败，请重试" finishBlock:nil];
        }
    }];
}


- (void)postDynamic:(NSString *)soundUrl{
    HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
    
    
    HRPostDynamicRequestModel *requestModel = [HRPostDynamicRequestModel new];
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    requestModel.MomentType = @"1";
    requestModel.MomentDetai = soundUrl;
    if (model.UserSoundUrl.length){
        requestModel.MomentNotes = @"";
    }else{
        requestModel.MomentNotes = @"我的Hearer声音名片";
    }
    
    requestModel.PositionName = ADDRESS;
    requestModel.MomentLength = self.timeStr;
    NSString *Longitude = @"0";
    if ([LONGITUDE length]){
        Longitude = LONGITUDE;
    }
    
    NSString *Latitude = @"0";
    if ([LATITUDE length]){
        Latitude = LATITUDE;
    }
    requestModel.Longitude = Longitude;
    requestModel.Latitude = Latitude;
    requestModel.Permission = 1;
    requestModel.CreateTime = [self getCurrentTime];
    
    [[HRPostDynamicViewModel  new] postDynamicRequstModel:requestModel isSeccess:^(HRDynamicModel *dynamicModel) {
        if (dynamicModel){
            
        }
    }];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
